const Router = require('koa-router')
const router = new Router()
const request = require('../../request')
const validator = require('../../middleware/validator')
const { toObject } = require('../../../utils')

module.exports = router

router.get('/recommendAuthor', validator({
  limit: {
    type: 'string',
    required: true,
    validator: (rule, value) => Number(value) > 0,
    message: 'limit 需传入正整数'
  }
}), async (ctx, next) => {
  ctx.set('Cache-Control', 'max-age=300')
  const  headers = ctx.headers
  const options = {
    url: 'https://web-api.juejin.im/query',
    method: "POST",
    headers: {
      'X-Agent': 'Juejin/Web',
      'X-Legacy-Device-Id': headers['x-device-id'],
      'X-Legacy-Token': headers['x-token'],
      'X-Legacy-Uid': headers['x-uid']
    },
    body: {
      operationName: "",
      query: "",
      variables: {
        limit: ctx.query.limit || 10,
        excluded: []
      },
      extensions: { query: { id: "b031bf7f8b17b1a173a38807136cc20e" } },
    }
  };
  let { body } = await  request(options, "获取推荐作者")

  body = toObject(body)
  console.log(body)
  try {
    ctx.body = {
      s: body.data.recommendationCard.items ? 1 : 0,
      d: body.data.recommendationCard.items
    }
  } catch (error) {
     ctx.body = {
       s: 0,
       d: [],
       errors: [body]
     }
  }
})

router.get('/books', async (ctx, next) => {
  const  headers = ctx.headers
  const options = {
    url: 'https://xiaoce-timeline-api-ms.juejin.im/v1/getRecommendBooks',
    method: 'GET',
    params: {
      src: 'web',
      uid: headers['x-uid'],
      client_id: headers['x-device-id'],
      token: headers['x-token'],
      category: '5562b428e4b00c57d9b94b9d'
    }
  }
  let { body } = await  request(options, "获取小册")
  ctx.body = body
})
